<template>
  <div class="documents-page">
    <el-card>
      <template #header>
        <div class="card-header">
          <h3>文档管理</h3>
          <el-button v-if="userStore.isAdmin" type="primary" @click="showUploadDialog">
            <el-icon><Upload /></el-icon>
            上传文档
          </el-button>
        </div>
      </template>

      <!-- 搜索 -->
      <el-row :gutter="20" style="margin-bottom: 20px">
        <el-col :span="12">
          <el-input
            v-model="searchQuery"
            placeholder="搜索文档标题或文件名..."
            clearable
            @input="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-col>
        <el-col :span="12">
          <el-statistic title="文档总数" :value="totalCount" />
        </el-col>
      </el-row>

      <!-- 文档列表 -->
      <el-table
        :data="displayedDocuments"
        border
        stripe
        style="width: 100%"
        v-loading="loading"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="title" label="标题" width="200" />
        <el-table-column prop="filename" label="文件名" width="200" show-overflow-tooltip />
        <el-table-column prop="file_type" label="类型" width="100">
          <template #default="{ row }">
            <el-tag :type="getFileTypeTag(row.file_type)">
              {{ row.file_type.toUpperCase() }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="file_size" label="大小" width="120">
          <template #default="{ row }">
            {{ formatFileSize(row.file_size) }}
          </template>
        </el-table-column>
        <el-table-column prop="upload_user" label="上传者" width="120" />
        <el-table-column prop="created_at" label="上传时间" width="180">
          <template #default="{ row }">
            {{ formatTime(row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              link
              @click="handleView(row)"
            >
              查看
            </el-button>
            <el-button
              v-if="userStore.isAdmin"
              type="danger"
              size="small"
              link
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-if="totalCount > pageSize"
        style="margin-top: 20px; justify-content: center"
        layout="prev, pager, next"
        :total="totalCount"
        :page-size="pageSize"
        v-model:current-page="currentPage"
        @current-change="handlePageChange"
      />
    </el-card>

    <!-- 上传文档对话框 -->
    <el-dialog
      v-model="uploadDialogVisible"
      title="上传文档"
      width="500px"
    >
      <el-form
        ref="uploadFormRef"
        :model="uploadForm"
        :rules="uploadRules"
        label-width="100px"
      >
        <el-form-item label="文档标题" prop="title">
          <el-input
            v-model="uploadForm.title"
            placeholder="请输入文档标题（可选，留空则使用文件名）"
          />
        </el-form-item>

        <el-form-item label="选择文件" prop="file">
          <el-upload
            ref="uploadRef"
            :auto-upload="false"
            :limit="1"
            :on-change="handleFileChange"
            :on-remove="handleFileRemove"
            accept=".txt,.md,.docx,.doc,.pdf,.csv,.xlsx,.xls"
          >
            <el-button type="primary">选择文件</el-button>
            <template #tip>
              <div class="el-upload__tip">
                支持 .txt, .md, .docx, .doc, .pdf, .csv, .xlsx, .xls 格式，文件大小不超过 16MB
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="uploadDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleUpload" :loading="uploading">
          上传
        </el-button>
      </template>
    </el-dialog>

    <!-- 查看文档对话框 -->
    <el-dialog
      v-model="viewDialogVisible"
      title="文档详情"
      width="800px"
      top="5vh"
    >
      <div v-if="currentDocument">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="标题" :span="2">
            {{ currentDocument.title }}
          </el-descriptions-item>
          <el-descriptions-item label="文件名">
            {{ currentDocument.filename }}
          </el-descriptions-item>
          <el-descriptions-item label="文件类型">
            <el-tag :type="getFileTypeTag(currentDocument.file_type)">
              {{ currentDocument.file_type.toUpperCase() }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="文件大小">
            {{ formatFileSize(currentDocument.file_size) }}
          </el-descriptions-item>
          <el-descriptions-item label="上传者">
            {{ currentDocument.upload_user }}
          </el-descriptions-item>
          <el-descriptions-item label="上传时间" :span="2">
            {{ formatTime(currentDocument.created_at) }}
          </el-descriptions-item>
        </el-descriptions>

        <el-divider />

        <h4>文档内容：</h4>
        <div class="document-content">
          {{ documentContent }}
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Upload, Search } from '@element-plus/icons-vue'
import api from '../api'
import { useUserStore } from '../store'

const userStore = useUserStore()

// 数据
const documents = ref([])
const loading = ref(false)
const searchQuery = ref('')
const currentPage = ref(1)
const pageSize = ref(10)

// 上传对话框
const uploadDialogVisible = ref(false)
const uploadFormRef = ref(null)
const uploadRef = ref(null)
const uploading = ref(false)
const uploadForm = ref({
  title: '',
  file: null
})

// 查看对话框
const viewDialogVisible = ref(false)
const currentDocument = ref(null)
const documentContent = ref('')

// 表单验证规则
const uploadRules = {
  // title 是可选的
}

// 计算属性
const filteredDocuments = computed(() => {
  if (!searchQuery.value) {
    return documents.value
  }
  
  const query = searchQuery.value.toLowerCase()
  return documents.value.filter(
    doc =>
      doc.title.toLowerCase().includes(query) ||
      doc.filename.toLowerCase().includes(query)
  )
})

const displayedDocuments = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredDocuments.value.slice(start, end)
})

const totalCount = computed(() => filteredDocuments.value.length)

// 方法
const loadDocuments = async () => {
  loading.value = true
  try {
    const response = await api.get('/documents')
    if (response.success) {
      documents.value = response.documents
    }
  } catch (error) {
    console.error('加载文档列表失败:', error)
    ElMessage.error('加载文档列表失败')
  } finally {
    loading.value = false
  }
}

const showUploadDialog = () => {
  uploadForm.value = {
    title: '',
    file: null
  }
  uploadDialogVisible.value = true
}

const handleFileChange = (file) => {
  uploadForm.value.file = file.raw
}

const handleFileRemove = () => {
  uploadForm.value.file = null
}

const handleUpload = async () => {
  if (!uploadForm.value.file) {
    ElMessage.warning('请选择要上传的文件')
    return
  }

  uploading.value = true

  try {
    const formData = new FormData()
    formData.append('file', uploadForm.value.file)
    if (uploadForm.value.title) {
      formData.append('title', uploadForm.value.title)
    }

    const response = await api.upload('/documents/upload', formData)

    if (response.success) {
      ElMessage.success('文档上传成功')
      uploadDialogVisible.value = false
      loadDocuments()
    } else {
      ElMessage.error(response.message || '上传失败')
    }
  } catch (error) {
    console.error('上传失败:', error)
    ElMessage.error('上传失败：' + (error.response?.message || error.message))
  } finally {
    uploading.value = false
  }
}

const handleView = async (row) => {
  try {
    const response = await api.get(`/documents/${row.id}`)
    if (response.success) {
      currentDocument.value = response.document
      documentContent.value = response.content || '暂无内容'
      viewDialogVisible.value = true
    } else {
      ElMessage.error('获取文档详情失败')
    }
  } catch (error) {
    console.error('获取文档详情失败:', error)
    ElMessage.error('获取文档详情失败')
  }
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除文档"${row.title}"吗？此操作不可恢复。`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const response = await api.delete(`/documents/${row.id}`)
    if (response.success) {
      ElMessage.success('文档已删除')
      loadDocuments()
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

const handleSearch = () => {
  currentPage.value = 1
}

const handlePageChange = () => {
  // 页码变化时，表格会自动更新
}

const getFileTypeTag = (type) => {
  const typeMap = {
    'txt': '',
    'md': 'success',
    'docx': 'primary',
    'doc': 'primary',
    'pdf': 'danger',
    'csv': 'warning',
    'xlsx': 'success',
    'xls': 'success'
  }
  return typeMap[type] || 'info'
}

const formatFileSize = (bytes) => {
  if (!bytes) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i]
}

const formatTime = (time) => {
  return new Date(time).toLocaleString('zh-CN')
}

onMounted(() => {
  loadDocuments()
})
</script>

<style scoped>
.documents-page {
  padding: 0;
  width: 100%;
  max-width: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0;
}

.card-header h3 {
  margin: 0;
  font-family: var(--font-family);
  font-size: var(--font-size-xl);
  font-weight: 500;
  color: var(--text-primary);
}

.document-content {
  background: #f5f5f5;
  padding: 15px;
  border-radius: 4px;
  max-height: 400px;
  overflow: auto;
  white-space: pre-wrap;
  word-wrap: break-word;
  font-family: monospace;
  font-size: 14px;
  line-height: 1.6;
}

:deep(.el-card) {
  border-radius: var(--radius-lg) !important;
  box-shadow: var(--shadow-sm) !important;
}

:deep(.el-card__body) {
  padding: var(--spacing-2xl) !important;
}

:deep(.el-table) {
  font-family: var(--font-family);
}

:deep(.el-button) {
  font-family: var(--font-family);
}

:deep(.el-input__inner) {
  font-family: var(--font-family);
}

:deep(.el-form-item__label) {
  font-family: var(--font-family);
  font-weight: 500;
  color: var(--text-primary);
}

:deep(.el-upload__tip) {
  font-size: 12px;
  color: #909399;
  margin-top: 7px;
}
</style>

